package com.sample.springbatch.job.sample.config;

import com.sample.springbatch.job.config.BaseConfig;
import com.sample.springbatch.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.listener.StepListenerSupport;
import org.springframework.batch.core.step.item.SimpleRetryExceptionHandler;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.database.JpaPagingItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.DataAccessException;
import org.springframework.integration.dsl.jpa.Jpa;
import org.springframework.retry.RetryCallback;
import org.springframework.retry.RetryContext;
import org.springframework.retry.RetryListener;
import org.springframework.retry.listener.RetryListenerSupport;
import org.springframework.retry.policy.NeverRetryPolicy;

import javax.persistence.EntityManagerFactory;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;


/**
 * Created by zwg on 2017/7/14.
 */
@Configuration
public class ExceptionJobConfig extends BaseConfig {

    Logger logger = LoggerFactory.getLogger(ExceptionJobConfig.class);

    @Autowired
    public EntityManagerFactory entityManagerFactory;

    @Bean(name = "exceptionJob")
    public Job exceptionJob(@Qualifier("exceptionStep") Step exceptionStep) {
        return jobBuilderFactory.get("exceptionJob")//job名称
                .start(exceptionStep)
                .build();
    }
    @Bean(name = "exceptionStep")
    public Step exceptionStep(@Qualifier("exceptionStepReader") JpaPagingItemReader reader,
                              @Qualifier("exceptionStepProcessor") ItemProcessor processor,
                              @Qualifier("exceptionStepWriter") ItemWriter writer){
        return stepBuilderFactory.get("exceptionStep")
                .chunk(1)
                .faultTolerant()
                //.noRetry(Exception.class)
                .retry(DataAccessException.class)
                .retryLimit(2)
                //.retryPolicy(new NeverRetryPolicy())
                .skip(NumberFormatException.class).skipLimit(2)
                .reader(reader)
                .processor(processor)
                .writer(writer)

                //.noSkip(Exception.class)
                //.skip(Exception.class)
                //.skipLimit(0)

                .build();
    }

    @Bean("exceptionStepReader")
    public JpaPagingItemReader<User> reader(){
        JpaPagingItemReader<User> reader = new JpaPagingItemReader<User>();
        reader.setQueryString("select b from User b where b.id < :id ");
        Map paramMap = new HashMap<>();
        paramMap.put("id", 10);
        reader.setParameterValues(paramMap);
        reader.setEntityManagerFactory(entityManagerFactory);
        reader.setSaveState(false);
        reader.setPageSize(10);
        return reader;
    }

    @Bean("exceptionStepProcessor")
    public ItemProcessor processor(){
        return new ItemProcessor<User,User>() {
            @Override
            public User process(User item) throws Exception {
                logger.info("item:{}",item);
                return item;
            }
        };
    }


    @Bean("exceptionStepWriter")
    public ItemWriter writer(){
        return new ItemWriter() {
            @Override
            public void write(List items) throws Exception {
                logger.info("begin writer:{}",items);
                Integer.valueOf("a");
                logger.info("end writer:{}",items);
            }
        };
    }



}
